package com.edyd.customer.api.controller;

import com.edyd.customer.api.context.ActionContext;
import com.edyd.customer.api.interceptor.LoginRequired;
import com.edyd.customer.api.domain.Customer;
import com.edyd.customer.api.request.LoginForm;
import com.edyd.customer.api.service.CustomerService;
import com.edyd.customer.api.view.SuccessView;
import com.fow.core.platform.crypto.MD5;
import com.fow.core.platform.web.rest.RESTController;
import com.fow.core.platform.web.rest.exception.InvalidRequestException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
public class CustomerController extends RESTController {

    private final Logger logger = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    private CustomerService customerService;

    @Autowired
    private ActionContext actionContext;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Customer Login(@Valid @RequestBody LoginForm form){

        Customer customer = customerService.selectByPhoneNum(form.getUserName());

        if (customer == null || !MD5.encrypt(form.getPassword()).equals(customer.getPassword()))
            throw new InvalidRequestException("用户名或密码错误!");

        autoSignIn(customer, customer.getId());
        return customer;
    }


    private void autoSignIn(Customer customer, int customerId) {


        customerService.updateCache(customer, customerId);
    }

    @RequestMapping(value="/customer",method = RequestMethod.GET)
    @ResponseBody
    @LoginRequired
    public Customer getCustomer() {

        Customer customer = actionContext.getCustomer();

        return customer;
    }


    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseBody
    @LoginRequired
    public SuccessView Logout(){
        Customer customer = actionContext.getCustomer();
        if(customer != null){
            customerService.deleteCache(customer, customer.getId());
        }

        return new SuccessView();
    }


}

